var gentry = null,
    hl = null,
    le = null;
var er = null,
    ep = null;
var bUpdated = false; //用于兼容可能提前注入导致DOM未解析完更新的问题
var fileSys;
var server = "https://7dtime.com/apix/z39base/upload";
// server = "http://192.168.0.100:8361/apix/z39base/upload";

// try{ if(isApp)initDcloudAudio() }catch(e){ console.log("app not ready") };
function initDcloudAudio() {
    if (gentry != null && fileSys != null) return console.log("声音已经初始化成功.");
    // 获取音频目录对象
    plus.io.resolveLocalFileSystemURL('_doc/z39/', function(entry) {
        entry.getDirectory('audio', { create: true }, function(dir) {
            gentry = dir;
            updateHistory();
        }, function(e) {
            console.log('Get directory "audio" failed: ' + e.message);
        });
    }, function(e) {
        console.log('Resolve "_doc/z39/" failed: ' + e.message);
    });

    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
        fileSys = fs;
    });
}

// 开始录音
var r = null,
    t = 0,
    ri = null,
    rt = null;
var audioNeedCancle = false;
var audioCurr, startTime, audioArr = [],
    audioIndex = 1;

function startRecord() {
    console.log('开始录音：');
    r = plus.audio.getRecorder();
    if (r == null) {
        console.error('录音对象未获取');
        return;
    }
    // audioCurr = { start: moment().format('HH:mm:ss') };
    // startTime = moment().valueOf();

    r.record({ filename: '_doc/z39/audio/',format: 'wav',samplerate: '8000' }, function(p) {
        console.log('录音完成：' + p);
        // audioCurr.end = moment().format('HH:mm:ss');
        // var now = moment().valueOf();
        // var time = Math.floor((now - startTime) / 1000).formatTime2();
        // audioCurr.duration = time;
        plus.io.resolveLocalFileSystemURL(p, function(entry) {
            if (audioNeedCancle) {
                entry.remove();
                audioNeedCancle = false;
            } else {
                audioIndex++;
                app.$store.commit({ type: "z39/mp3Add", "mp3Curr": { file: p, urllocal: entry.toRemoteURL() } });
                // audioCurr.title = "录音 " + audioIndex;
                // audioArr.unshift(audioCurr);
                // update2vue();
            }

        }, function(e) {
            console.log('读取录音文件错误：' + e.message);
        });
    }, function(e) {
        console.log('录音失败：' + e.message);
    });
    t = 0;
    // ri = setInterval(function() {
    //   t++;
    //   updateRecode();
    // }, 1000);
}

// 上传音频
function audioUpload(item,token) {
    if (item.url) return plus.nativeUI.toast('已经上传');
    if (!item.file || !item.id) return plus.nativeUI.toast('缺少参数');
    //var wt = plus.nativeUI.showWaiting();
    var task = plus.uploader.createUpload(server, { method: "POST" },
        function(t, status) { //上传完成
            if (status == 200) {
                //wt.close();
                var data = JSON.parse(t.responseText);
                // console.log("upload:", t.responseText, JSON.stringify(data));
                if (data.errno != 0) return plus.nativeUI.toast(data.errmsg);
                app.$store.commit({ type: "z39/mp3Update", "mp3item": { id: item.id, url: data.data } });
            } else {                
                //wt.close();   // outLine("上传失败："+status);
            }
        }
    );
	console.log("audioUpload:", token);    
	token = token||localStorage.getItem('token') || '';
    task.addData("token", token);
    task.addData("uid", item.uid);
	for(var key in item){
		task.addData(key, "" + item[key]);
	}
    task.addFile(item.file, { key: item.title, sid: item.id});
    task.start();
    // console.log("item.file:", item.file);    
}

function audioCancle() {
    audioNeedCancle = true;
    stopRecord();
}
// 删除音频
function audioDel(path) {
    console.log("in del change:", fileSys, path);
    try {
        plus.io.resolveLocalFileSystemURL(path, function(fileEntry) {
            if (fileEntry.isFile) {
                fileEntry.remove(function(entry) {
                    console.log("Audio Remove succeeded", path);
                    var len = audioArr.length;
                    for (var i = 0; i <= len - 1; i++) {
                        var item = audioArr[i];
                        if (item.file == path) {
                            audioArr.splice(i, 1);
                            update2vue();
                            break;
                        }
                    }
                }, function(e) {
                    alert(e.message);
                });
            } else {
                //适当提示，根据需求来
                mui.toast("不是文件")
            }
        }, function(e) {
            alert("Remove file URL failed: " + e.message);
        });
    } catch (e) {
        consolo.log("audiodel", e);
    }
}

function local2remote(path) {
    var res = '';
    fileSys.root.getFile(path, { create: true }, function(fileEntry) {
        //res = fileEntry.toURL() ;
        res = fileEntry.toRemoteURL();
        console.log("url" + fileEntry.toURL() + fileEntry.toLocalURL() + fileEntry.toRemoteURL());
    });
    return res;
}

// function updateRecode() {
//   try {
//     var now = moment().valueOf();
//     var time = Math.floor((now - startTime) / 1000).formatTime2();
//     audioCurr.duration = time;
//     app.$store.commit({ type: "z39/mp3Curr", "mp3Curr": audioCurr });
//   } catch (e) {
//     console.warn("vue not ready", e);
//   }
// }

// 停止录音
function stopRecord() {
    clearInterval(ri);
    ri = null;
    r.stop();
    w = null;
    r = null;
    t = 0;
}

// 清除历史记录
function cleanHistory() {
    // 删除音频文件
    console.log('清空录音历史记录：');
    gentry.removeRecursively(function() {
        // Success
        console.log('操作成功！');
    }, function(e) {
        console.log('操作失败：' + e.message);
    });
}
var audioItem = { title: "", desc: "", img: "", duration: "", urllocal: "", url: "" };

// 获取录音历史列表
function updateHistory() {
    if (bUpdated || !gentry || !document.body) { //兼容可能提前注入导致DOM未解析完更新的问题
        return;
    }
    console.log("get audio in");
    var reader = gentry.createReader();
    reader.readEntries(function(entries) {
        audioArr = [];
        var tempPlayer, dur, tempurl, filePath;
        var entry;
        for (var i in entries) {
            entry = entries[i];
            if (entry.isFile) {
                tempurl = '_doc/z39/audio/' + entry.name;
                filePath = tempurl;
                tempPlayer = plus.audio.createPlayer(tempurl);
                dur = tempPlayer.getDuration();
                tempurl = entry.toRemoteURL(); // local2remote(tempurl) ;
                console.log("tempurl : " + tempurl);
                dur = dur.formatTime();
                audioIndex = (parseInt(i) + 1);
                audioArr.unshift({ title: "录音 " + audioIndex, desc: "", img: "", duration: dur, file: filePath, urllocal: tempurl, url: "" });
            }
        }
        update2vue();
    }, function(e) {
        console.log('读取录音列表失败：' + e.message);
    });
    bUpdated = true;
}

function update2vue() {
    try {
        app.$store.commit({ type: "z39/mp3Arr", "mp3Arr": audioArr });
    } catch (e) {
        console.warn("vue not ready", e);
    }
}

// 格式化秒数到时间格式
Number.prototype.formatTime2 = function() {
    // 计算
    var h = 0,
        i = 0,
        s = parseInt(this);
    if (s > 60) {
        i = parseInt(s / 60);
        s = parseInt(s % 60);
        if (i > 60) {
            h = parseInt(i / 60);
            i = parseInt(i % 60);
        }
    }
    // 补零
    var zero = function(v) {
        return (v >> 0) < 10 ? "0" + v : v;
    };
    if (h > 0) {
        return [zero(h), zero(i), zero(s)].join(":");
    } else {
        return [zero(i), zero(s)].join(":");
    }
};

// 格式化秒数到时间格式
Number.prototype.formatTime3 = function() {
    // 计算
    var h = 0,
        i = 0,
        s = parseInt(this);
    if (s > 60) {
        i = parseInt(s / 60);
        s = parseInt(s % 60);
        if (i > 60) {
            h = parseInt(i / 60);
            i = parseInt(i % 60);
        }
    }
    // 补零
    var zero = function(v) {
        return (v >> 0) < 10 ? "0" + v : v;
    };
    if (h > 0) {
        return [zero(h), zero(i), zero(s)].join(":");
    } else {
        return [zero(h), zero(i), zero(s)].join(":");
    }
};